#include "Scheduler.h"
#include "Event.h"
#include "Shell.h"
#include "Universe.h"
#include "SimpleCollisionSolver.h"

Scheduler::Scheduler(Universe * universe) : 
     universe(universe), collisionSolver(new SimpleCollisionSolver(universe))
{
}

Scheduler::~Scheduler()
{
    delete collisionSolver;
}

void Scheduler::executeTimeFrame()
{
    std::list<Event *>::iterator iter;
    Shell * shell;
      
    // solve conficts here...
    collisionSolver->solveCollisions(organised);

    generateFrame();
        
    while(organised.size() > 0)
    {
        // get first Event
        iter = organised.begin();
        
        shell = (*iter)->getShell();
        

        universe->moveElementTo(shell, (*iter)->position);

        organised.pop_front();
    }
}
    
void Scheduler::scheduleEvent(Event * event)
{   
    schedule.push_back(event);
}

// Sigma, add events of the same Ghost
void Scheduler::generateFrame()
{
    std::list<Event *>::iterator iter;
    Event * sum;

    organised.clear();
    
    // add all objects that are the same
    while(schedule.size() > 0)
    {
        // get first Event
        sum = schedule.front();
        schedule.pop_front();
        
        iter = schedule.begin();
        while(iter != schedule.end())
        {
            // if the same object
            if((*iter)->equalsShell(sum->getShell()))
            {
                //add the Event in the iterator to the sum
//                (*sum) += (*(*iter));


                std::cout << "object tries to do multiple stuff" << std::endl;
                
                schedule.erase(iter);
            }
            /* otherwise skip this one */
            else
                ++iter;
        }
        organised.push_back(sum);
    }
}

